<template>
    <WidgetContainer :widget-id="config.id">
        <FormItemWidget :config="config" :rowIndex="rowIndex" :parentId="parentId">
            <el-switch :class="config.attributes?.cssClass" inline-prompt v-model="fieldValue" :disabled="config.attributes.disabled"
                :active-text="config.attributes.activeText" :inactive-text="config.attributes.inactiveText"
                :active-value="config.attributes.activeValue" :inactive-value="config.attributes.inactiveValue"
                :size="config.attributes.size" :style="{ width: config.attributes.width }" @change="handleChange" />
        </FormItemWidget>
    </WidgetContainer>
</template>

<script setup>
import { ElSwitch } from 'element-plus';
import { inject, onMounted } from 'vue';
import { executeEventHandler } from '@/utils/eventExecutor'
import { useFieldBinding } from '@/utils/useFieldBinding'

const formData = inject('formData')
const widgetList = inject('widgetList')

const props = defineProps({
    config: Object,
    rowIndex: Number,
    parentId: String
})

const { fieldValue } = useFieldBinding(formData, props.config, {
    rowIndex: props.rowIndex,
    parentId: props.parentId
})

onMounted(() => {
    executeEventHandler(props.config.events?.onMounted,
        { widgetConfig: props.config, formData: formData.value, widgetList: widgetList.value }
    )
})

const handleChange = (value) => {
    executeEventHandler(props.config.events?.onChange,
        { widgetConfig: props.config, formData: formData.value, widgetList: widgetList.value, value }
    )
}
</script>